package com.ilovepostcard;

import java.io.FileOutputStream;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.Toast;

import com.ilovepostcard.controller.PostcardController;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.ShareController;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.model.ShareTextConfig;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.ImageUtil;
import com.ilovepostcard.utils.ThirdPartyLoginUtil;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.PostcardMainMenu;
import com.mobclick.android.MobclickAgent;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.weibo.net.AccessToken;
import com.weibo.net.Weibo;

public class SharekActivity extends MenuActivity implements OnClickListener{
	
	ImageButton sentToOther; 
	ImageButton sentRealPC; 
	long pid;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share);
		init();
		pid = getIntent().getExtras().getLong("pid");
		
	}
	
	public void onBackPressed () 
	{
		Intent intent = new Intent(this,MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		this.startActivity(intent);
		
	}
	

	protected void onResume()
	{
		super.onResume();
		MobclickAgent.onResume(this); 
	}
	
	protected void onPause()
	{
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		ShareController.getInstance().cancelCurrentSendTask();
	}
	
	private static String randomStringFrom(String[] strs) {
        int length = strs.length;
        Random random = new Random(System.currentTimeMillis());
        int index = random.nextInt(length);
        return strs[index];
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ThirdPartyLoginUtil.TENCENT_SHARE_REQUEST_CODE) {
            if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
                // 取得返回的OAuthV2类实例oAuth
                final OAuthV2 oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
                
                new ServerAsyncTask(SharekActivity.this) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {

                            String filePath = null;
                            
                            Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
                            filePath = postcard.getTmpEditPCViewPath();
                            /*FileOutputStream fos = null;
                            try {
                            Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
                            filePath = postcard.getEditPCPath();
                            if (postcard != null && postcard.image != null) {
                                fos = new FileOutputStream(Constants.TEMP_SHARE_IMAGE_PATH);
                                postcard.pcView.compress(CompressFormat.JPEG, 100, fos);
                                filePath = Constants.TEMP_SHARE_IMAGE_PATH;
                            }
                            } catch(Exception e) {
                                
                            } finally {
                                if (fos != null) {
                                    try {
                                        fos.close();
                                    } catch(Exception exception) {
                                        
                                    }
                                }
                            }*/
                            
                        ShareTextConfig shareTextConfig = result.getShareTextConfig2();
                        String config = shareTextConfig.Body;
                        
                        TAPI tapi = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
                        try {
//                            tapi.add(oAuth, "json", config, "");
                        	
                            tapi.addPic(oAuth, "json", config, "",filePath /*shareTextConfig.PostcardUrl*/);
                            Toast.makeText(SharekActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        User loginUser = UserController.getLoginUser(context);
                        return ServerFactory.getServer().getShareTextConfig(IServer.TEXT_CONFIG_TYPE_SHARE, loginUser.UserID, pid);
                    }
                }.execute();
                
                

            }
            return;
        }
		
		if (resultCode != RESULT_OK) 
		{
			Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
			return;
		}
			
		
		Bitmap bm = null;
		Uri uri = null;
		try {
			
			if (requestCode == ImageUtil.GALLERY) {
				uri = data.getData();
				
			} 
	    	else if (requestCode == ImageUtil.CAMERA)
	    	{
	    		uri = ImageUtil.getImageFromCamera(this);
	    	}
		} 
		catch (Exception e) {
			Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
		}
		
		
		if(bm != null || uri!= null)
		{
			Intent intent = new Intent(this, EditImageActivity.class);
			Bundle bundle =new Bundle();
			String from = "camera";
			if(uri != null)
				from = "gallery";
			bundle.putString("type",from);
			bundle.putParcelable("uri", uri);
			
			intent.putExtras(bundle);
	        startActivity(intent);
		}
	
		
	}
	
	private void init()
	{
		sentToOther = (ImageButton)findViewById(R.id.send_other);
		sentToOther.setOnClickListener(this);

		sentRealPC = (ImageButton)findViewById(R.id.send_realpc);
		sentRealPC.setOnClickListener(this);
		
		View sendSina = findViewById(R.id.send_sina);
		sendSina.setOnClickListener(this);
		
		View sendTencent = findViewById(R.id.send_ten);
		sendTencent.setOnClickListener(this);
		
		View sendWeixin = findViewById(R.id.send_weixin);
		sendWeixin.setOnClickListener(this);
		
		View sendOther = findViewById(R.id.send_other);
		sendOther.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.send_realpc)
		{
			MobclickAgent.onEvent(this, Constants.COUNT_CREAT_PRINT);
			Intent nextPage = new Intent(SharekActivity.this,PrintChangeTypeActivity.class);
			SharekActivity.this.startActivity(nextPage);
		}
		else if (v.getId() == R.id.send_sina) {
			MobclickAgent.onEvent(this, Constants.COUNT_CREAT_SHARE_SINA);
		    ThirdPartyLoginUtil.shareToSinaWeibo(SharekActivity.this, pid);
		}
		else if (v.getId() == R.id.send_ten) {
			MobclickAgent.onEvent(this, Constants.COUNT_CREAT_SHARE_QQ);
		    ThirdPartyLoginUtil.shareToTencent(SharekActivity.this, pid);
		}
		else if (v.getId() == R.id.send_weixin) {
			MobclickAgent.onEvent(this, Constants.COUNT_CREAT_SHARE_WEIXIN);
		    ThirdPartyLoginUtil.shareToWeiXin(SharekActivity.this, pid);
		}
		else if (v.getId() == R.id.send_other) {
			MobclickAgent.onEvent(this, Constants.COUNT_CREAT_SHARE_OTHER);
		    ThirdPartyLoginUtil.shareToOther(SharekActivity.this, pid);
		}
	}

}
